<!-- 上传文件到cos -->
<template>
	<div>
		<div @click="chooseImage">
			<slot></slot>
		</div>
		<l-clipper v-if="show" :imageUrl="imageUrl" @success="getImage" @cancel="show = false" />
	</div>
</template>

<script>
	import configs from '@/config/config.js'
	import uploadFile from '@/js_sdk/tencentcloud-plugin-cos/upload-file';
	export default {
		data() {
			return {
				show: false,
				configs,
				imageUrl: '',
			}
		},
		props: {
			name: {
				type: String,
				default () {
					return '';
				}
			}
		},
		onShow() {

		},
		methods: {
			async getImage(e) {
				console.log(e)
				var that = this;
				that.show = false
				const key = await uploadFile(e.url); // 返回的key即上传到COS的图片文件名（不包含域名部分，一般用来提交给后台接口保存到数据库）
				const url = configs.uploadImg + key; // 返回的url即前面上传到COS的图片的访问地址（包含临时签名）
				that.$emit('getdata', {
					key: key,
					url: url
				})
			},
			chooseImage() {
				var that = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					success: res => {
						console.log(res);
						that.imageUrl = res.tempFilePaths[0]
						that.$nextTick(() => {
							that.show = true
						})
						// that.uploadimg(res.tempFilePaths[0]);
					},
					fail: err => {
						// #ifdef MP
						uni.getSetting({
							success: res => {
								let authStatus = res.authSetting['scope.album'] && res.authSetting[
									'scope.camera'];
								if (!authStatus) {}
							}
						});
						// #endif
					}
				});
			},
			uploadimg(url) {
				var that = this;
				if (uni.getStorageSync('token')) {
					let a = uni.uploadFile({
						url: configs.uploadPic, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'pic',
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync('token')
						},
						success: (res) => {
							console.log(res)
							console.log(JSON.parse(res.data))
							console.log(1234)
							that.$emit('getdata', JSON.parse(res.data).data)
							if (JSON.parse(res.data).code == 401) {
								uni.redirectTo({
									url: '/pages/login/login'
								})
							}
						},
						fail: (res) => {
							if (res.code == 401) {
								uni.redirectTo({
									url: '/pages/login/login'
								})
							}
						}
					});
				} else {
					uni.redirectTo({
						url: '/pages/login/login'
					})
				}
			}
		}
	}
</script>

<style>
</style>
